package org.arain.baseii.system.role;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.arain.baseii.aspect.annotation.SystemExceptionLog;
import org.arain.baseii.aspect.annotation.SystemServiceLog;
import org.arain.baseii.common.CommonServiceImpl;
import org.arain.baseii.grid.GridData;
import org.arain.baseii.grid.QueryParam;
import org.arain.baseii.mapper.SysResourceMapper;
import org.arain.baseii.mapper.SysRoleMapper;
import org.arain.baseii.mapper.SysRoleResourceMapper;
import org.arain.baseii.pojo.SysResource;
import org.arain.baseii.pojo.SysRole;
import org.arain.baseii.pojo.SysRoleExample;
import org.arain.baseii.pojo.SysRoleExample.Criteria;
import org.arain.baseii.pojo.SysRoleResource;
import org.arain.baseii.pojo.SysRoleResourceExample;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.ArainResult;
import org.arain.baseii.utils.DictUtil;
import org.arain.baseii.utils.IDUtil;
import org.arain.baseii.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

/**
 * 
* <p>Title:SysRoleController </p>
* @author Arain
* @date2017年8月31日
 */
@Service
public class SysRoleServiceImpl extends CommonServiceImpl<SysRoleDto> implements SysRoleService{
	@Autowired
	private SysRoleMapper sysRoleMapper;
	
	@Autowired
	private SysResourceMapper sysResourceMapper;
	
	@Autowired
	private SysRoleResourceMapper sysRoleResourceMapper;
	
	@Value("${ADMIN}")
	private Long admin;
	@Override
	public String load_grid(QueryParam param) {
		SysRoleDto dto = new SysRoleDto();
		try {
			dto = this.jsonToObject(param.getFilterRules(),dto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONArray array = new JSONArray();
		SysRoleExample example = new SysRoleExample();
		Criteria criteria = example.createCriteria().andOrgidEqualTo(AppUtils.getOrgId()).andIdNotEqualTo(admin);
		if(StringUtils.isNotBlank(param.getOrder()) && StringUtils.isNotBlank(param.getSort())) {
			example.setOrderByClause(param.getSort()+" "+param.getOrder());
		}
		if(StringUtils.isNotBlank(dto.getName())) {
			criteria.andNameLike("%"+dto.getName()+"%");
		}
		if(StringUtils.isNotBlank(dto.getEnabled())) {
			criteria.andEnabledEqualTo(Short.valueOf(dto.getEnabled()));
		}
		PageHelper.startPage(param.getPage(), param.getRows());
		List<SysRole> list = sysRoleMapper.selectByExample(example);
		int countByExample = sysRoleMapper.countByExample(example);
		for (SysRole sysRole : list) {
			JSONObject object = new JSONObject();
			object.put("id", sysRole.getId());
			object.put("name", sysRole.getName());
			object.put("sort", sysRole.getSort());
			object.put("operator", sysRole.getOperator());
			object.put("opTime", TimeUtil.format(sysRole.getOpTime()));
			object.put("enabled", DictUtil.load_dict(sysRole.getEnabled()+"", "ENABLED_").getDispaly());
			
			array.add(object);
		}
		GridData data = new GridData();
		data.setTotal(countByExample);
		data.setRows(array);
		return GridData.gridToJson(data);
	}
	@Override
	public String load_role_resource(SysRoleDto dto) {
		if(StringUtils.isNotBlank(dto.getId()) && !"null".equals(dto.getId())) {
			SysRoleResourceExample example = new SysRoleResourceExample();
			example.createCriteria().andCheckedEqualTo((short) 1).andRoleIdEqualTo(Long.valueOf(dto.getId()));
			List<SysRoleResource> role_resource_list = sysRoleResourceMapper.selectByExample(example);
			
			JSONArray array = new JSONArray();
			Long userId = AppUtils.getUserId();
			List<SysResource> list = sysResourceMapper.selectAllButtonByUserID(userId);
			for (SysResource sysResource : list) {
				JSONObject object = new JSONObject();
				object.put("id", sysResource.getId());
				object.put("text", sysResource.getName());
				if (sysResource.getPid() != 0) {
					object.put("pid", sysResource.getPid());
				}
				in:for (SysRoleResource checked : role_resource_list) {
					if(sysResource.getId().equals(checked.getResourceId())) {
						object.put("checked",sysResource.getId());
						break in;
					}
				}
				
				array.add(object);
			}
			return array.toString();
			
		}else {
			JSONArray array = new JSONArray();
			Long userId = AppUtils.getUserId();
			List<SysResource> list = sysResourceMapper.selectAllButtonByUserID(userId);
			for (SysResource sysResource : list) {
				JSONObject object = new JSONObject();
				object.put("id", sysResource.getId());
				object.put("text", sysResource.getName());
				if (sysResource.getPid() != 0) {
					object.put("pid", sysResource.getPid());
				}
				
				array.add(object);
			}
			return array.toString();
		}
	}
	@Override
	@SystemExceptionLog(description="保存")
	@SystemServiceLog(description="保存")
	public ArainResult save_01(SysRoleDto dto) {
		if(StringUtils.isNotBlank(dto.getId())) {
			SysRole sysRole = new SysRole();
			AppUtils.copyProperties(sysRole, dto);
			sysRole.setOperator(AppUtils.getUserName()+"||"+AppUtils.getRealName());
			sysRole.setOpTime(new Date());
			sysRoleMapper.updateByPrimaryKey(sysRole);
			
			SysRoleResourceExample roleResourceExample = new SysRoleResourceExample();
			roleResourceExample.createCriteria().andRoleIdEqualTo(sysRole.getId());
			sysRoleResourceMapper.deleteByExample(roleResourceExample);
			
			net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(dto.getResourceIds());
			for (int i = 0; i < array.size(); i++) {
				net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(array.get(i));
				SysRoleResource sysRoleResource=new SysRoleResource();
				sysRoleResource.setChecked((short) jsonObject.getInt("checked"));
				sysRoleResource.setResourceId(jsonObject.getLong("resourcesIds"));
				sysRoleResource.setRoleId(sysRole.getId());
				sysRoleResourceMapper.insert(sysRoleResource);
			}
			return ArainResult.ok();
		} else {
			SysRole sysRole = new SysRole();
			AppUtils.copyProperties(sysRole, dto);
			sysRole.setId(Long.valueOf(IDUtil.genId()));
			sysRole.setOperator(AppUtils.getUserName()+"||"+AppUtils.getRealName());
			sysRole.setOpTime(new Date());
			sysRoleMapper.insert(sysRole);
			
			net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(dto.getResourceIds());
			for (int i = 0; i < array.size(); i++) {
				net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(array.get(i));
				SysRoleResource sysRoleResource=new SysRoleResource();
				sysRoleResource.setChecked((short) jsonObject.getInt("checked"));
				sysRoleResource.setResourceId(jsonObject.getLong("resourcesIds"));
				sysRoleResource.setRoleId(sysRole.getId());
				sysRoleResourceMapper.insert(sysRoleResource);
			}
			return ArainResult.ok();
		}
	}
	@Override
	public SysRoleDto load_01(SysRoleDto dto) {
		SysRole role = sysRoleMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		AppUtils.copyProperties(dto, role);
		return dto;
	}
}
